/* global window */
import { router } from 'utils'
import { stringify } from 'qs'
import store from 'store'
// import { ROLE_TYPE } from 'utils/constant'
import { pathMatchRegexp } from 'utils'
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant'
import api from 'api'
import { message } from 'antd'
import { pageModel, model } from 'utils/model'
import modelExtend from 'dva-model-extend'
const {} = api
const regionstate = {
  windowToken: '',
  subSocket: undefined,
}
export default modelExtend(model, {
  namespace: 'socket',
  state: {
    ...regionstate,
  },
  subscriptions: {
    setup({ dispatch }) {
      var windowToken = Math.random()
        .toString(10)
        .substr(5)
      dispatch({ type: 'updateState', payload: { windowToken } })
    },
  },
  effects: {
    *heartbeat({ payload }, { call, put, select }) {
      const { subSocket, windowToken, user } = yield select(_ => _.app)
      if (subSocket) subSocket.send('hb:' + user.objectId + ':' + windowToken)
    },

    *sendMsg({ payload }, { call, put, select }) {
      const { subSocket, user } = yield select(_ => _.app)
      if (subSocket)
        subSocket.send(
          JSON.stringify({ author: user.objectId, message: payload.msg })
        )
    },

    *closeWs({ payload }, { call, put, select }) {
      const { subSocket } = yield select(_ => _.app)
      if (subSocket) subSocket.close()
      yield put({ type: 'updateState', payload: { subSocket: undefined } })
    },
  },
  reducers: {},
})
